<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新品有戏后台管理</title>
    <script src="__JS__/jquery.js"></script>
    <link href="__CSS__/boot.css" rel="stylesheet">
    <link href="__STATIC__/layui/css/layui.css" rel="stylesheet">
    <script src="__JS__/layer/layer.js"></script>
    <script src="__STATIC__/layui/layui.js"></script>
    <script src="__STATIC__/boot/js/bootstrap-table.js"></script>
    <script src="__STATIC__/boot/js/bootstrap-table-zh-CN.min.js"></script>
    <script src="__STATIC__/boot/js/dropdown.js"></script>
    <link rel="stylesheet" href="__STATIC__/boot/css/bootstrap-table.min.css"/>
    <style>
        td {
            text-align: center;
        }
    </style>
</head>
<body>
{include file="base/header" /}
<div>
    <div style="width: 700px ;float: left">
        <button class="layui-btn" onclick="look({$id})">查看购买记录</button>
        <button class="layui-btn layui-btn-normal" onclick="count({$id})">统计</button>&nbsp;&nbsp;&nbsp;&nbsp;
        <i class="layui-icon" id="add" onclick="add({$id})" onmouseover="over(this)" onmouseout="out(this)"  style="font-size: 30px;">&#xe61f;</i>&nbsp;&nbsp;&nbsp;&nbsp;
        <i class="layui-icon" id="del" onclick="del()"  onmouseover="over(this)" onmouseout="out(this)"  style="font-size: 30px;">&#xe640;</i>&nbsp;&nbsp;&nbsp;&nbsp;
        <i class="layui-icon" id="edit" onclick="edit()"  onmouseover="over(this)" onmouseout="out(this)"  style="font-size: 30px;">&#xe642;</i>
        <table id="tea"></table>
    </div>
    <div style="width: 640px ;float: right;" id="buyinfo">

    </div>
    <div style="width:500px;margin: 0 auto;" id="total">
        <input type="button" class="btn btn-primary " value="总金额(元)"/>：<label id="tal" style="width: 50px"></label>
        <input type="button" class="btn btn-primary " onclick="settlement({$id})" value="结账">
    </div>

</div>
</body>
<script>
    /**
     * 用于存储购买的信息
     * */

    total = [];

    $('#tea').bootstrapTable({
            //获取行号
            onClickRow: function(row, $element) {
                indexs = $element.data('index');
                //console.log(row);
            },
            language: 'zh-CN',
            autoclose: true,
            todayHighlight: true,
            striped: true,//设置为 true 会有隔行变色效果
            method: 'get',//服务器数据的请求方式 'get' or 'post'
            url: "{:url('index/tea/info')}?sid="+{$id},//服务器数据的加载地址
            //contentType: "application/x-www-form-urlencoded",//发送到服务器的数据编码类型
            toolbar:'#toolbar',//
            //selectItemName:'checkbox',
            //search:'true',//
            searchText:'',//搜索字段
            trimOnSearch:'true',//搜索时去掉空格
            searchOnEnterKey:true,
            sortName:'ID',//排序字段
            sortOrder : 'desc',//降序
            //showToggle: 'true',//是否显示 切换试图（table/card）按钮
            // showColumns: 'true',//是否显示 内容列下拉框
            //showRefresh:"false",//刷新
            sidePagination: "server",   //分页方式：client客户端分页，server服务端分页（*）
            pagination: 'false',//设置为 true 会在表格底部显示分页条
            //clickToSelect:'true',//设置true 将在点击行时，自动选择rediobox 和 checkbox
            singleSelect:'true',//设置True 将禁止多选
            pageSize: '20',//如果设置了分页，页面数据条数
            pageList:[20,40],
            smartDisplay:false,
            //得到查询的参数
            queryParams : function (params) {
                //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    //sort: params.sort,      //排序列名
                    //sortOrder: params.order,//排位命令（desc，asc）
                    title:params.search
                };
                return temp;
            },
            columns: [
                {align:'center',title:'请选择',formatter : check},
                {field: 'id', title: 'ID', align:'center'},
                {field: 'name', title: '名称', align:'center'},
                {align:'center',title: '价格', formatter:large},
                // {align:'center',title: '价格(中杯)', formatter:ins},
                // {align:'center',title: '价格(小杯)', formatter:small},
                {align:'center',title: '图片',formatter:images}
            ]
        }
    );
    /**
     * 请选择按钮
     * */
    function check(value,row,index) {
        return '<input type="radio" name="check" value="'+row.id+'">';
    }
    /**
     * 大
     * */
    function large(value,row,index) {
        return[
            row.largeprice,
            '<i class="layui-icon" id="'+row.id+'" onclick="buy('+row.id+','+1+')" style="font-size: 20px; color: black;">&#xe623;</i>'
        ].join('');
    }
    /**
     * 中
     * */
    function ins (value,row,index) {
        return [
            row.inprice,
            '<i class="layui-icon" id="'+row.id+'" onclick="buy('+row.id+','+2+')" style="font-size: 20px; color: blue;">&#xe623;</i>'
        ].join('');
    }
    /**
     * 小
     * */
    function small(value,row,index) {
        return[
            row.smallprice,
            '<i class="layui-icon" id="'+row.id+'" onclick="buy('+row.id+','+3+')" style="font-size: 20px; color: red;">&#xe623;</i>'
        ].join('');

    }
    /**
     * 图片
     * */
    function images(value,row,index){
        return '<img  src="__ROOT__\\'+row.image+'" width="50" height="50" class="img-rounded" >';
    }
    /**
     * 删除
     * */
    function del() {
        var id = $("input[name=check]:checked").val();
        if(!id){
            layer.msg('请选择需要删除信息的按钮',{icon:5,time:2000});
            return;
        }
        layer.confirm('你确定要删除吗',{btn:['确定','取消'],skin: 'demo-class'},function () {
            $.ajax({
                url:"{:url('index/tea/del')}",
                data:"id="+id,
                type:"post",
                dataType:"json",
                success:function (res) {
                    if(res.success){
                        console.log(indexs);
                        layer.msg(res.success,{ icon: 1,time:1000});
                        num = indexs + 1;
                        $("#tea").find("tr:eq("+num+")").remove();
                    }
                    if(res.error){
                        layer.msg(res.error,{icon:2,time:3000});
                    }
                }
            });
        })
    }
    /**
     * 编辑
     * */
    function edit() {
        var id = $("input[name=check]:checked").val();
        if(!id){
            layer.msg('请选择需要修改信息的按钮',{icon:5,time:2000});
            return;
        }
        layer.open({
            type:2,
            title:'编辑',
            area: ['800px', '600px'],
            content:"{:url('index/tea/edit')}?id="+id
        });
    }
    /**
     * 添加
     * */
    function add(id) {
        layer.open({
            type:2,
            title:"添加",
            area:['800px','600px'],
            content:"{:url('index/tea/add')}?sid="+id
        });
    }
    /**
     *购买中杯
     * */
    function buy(id,num) {

        $.ajax({
            url:"{:url('index/tea/buyinfo')}",
            data:{
                'id':id,
                'num':num
            },
            type:"post",
            dataType:"json",
            success:function (res) {
                if(res.info){
                    buyinfo(res);
                }else if(res.error){
                    layer.alert(res.error);
                }
            }
        });
    }

    /**
     * 展示购买信息
     * */
    function buyinfo(res) {
        //表格id
        var tableid = res.info.id + res.num;
        //购买数量id
        var numid = res.info.id + res.num;
        if(ifArrVal(total,res.info.id) && ifArrVal(total,res.num)){
            for(var i=0;i<total.length;i++){
                if(contains(total[i],res.info.id) && contains(total[i],res.num)){
                    total[i][4] += 1;
                    total[i][5] += total[i][2];
                    $("#num"+res.info.id+res.num).val(total[i][4]);
                    //console.log(total);
                    compute();
                    return;
                }
            }
        }
        var table = "<table width='500px' class='layui-table' id=table"+tableid+">";
        table += "<tr>";
        table += "<td>茶名称</td><td>单价(元)</td><td>类别</td><td>个数</td><td>操作</td>";
        table += "</tr>";
        table += "<tr>";
        table += "<td>"+res.info.name+"</td>";
        if(res.num == 1){
            table += "<td>"+res.info.largeprice+"</td>";
            table += "<td>大杯</td>";
        }else if(res.num == 2){
            table += "<td>"+res.info.inprice+"</td>";
            table += "<td style='color: blue'>中杯</td>";
        }else if(res.num == 3){
            table += "<td>"+res.info.smallprice+"</td>";
            table += "<td style='color: red'>小杯</td>";
        }
        table += '<td><input type="button" class="btn btn-info" id="'+res.info.id+'" onclick="plus('+res.info.id+','+res.num+')" value="+"/><input type="text" value="1" id="num'+numid+'" style="width: 40px;height: 30px;text-align: center; border: 0px;" readonly/><input type="button" onclick="reduce('+res.info.id+','+res.num+')" value="-" class="btn btn-info" /></td>';
        table += '<td><button type="button" class="btn btn-danger" onclick=tabledel('+res.info.id+','+res.num+') id="table'+res.info.id+'">删除</button></td>';
        table += "</tr>";
        table += "</table>";
        var single = [];
        //购买个数
        var number = 1;
        //单个总计
        var price = 0;
        //0
        single.push(res.info.id);
        //1
        single.push(res.info.name);
        //2
        if(res.num == 1){
            single.push(res.info.largeprice);
            price = res.info.largeprice;
        }else if(res.num == 2){
            single.push(res.info.inprice);
            price = res.info.inprice;
        }else if(res.num){
            single.push(res.info.smallprice);
            price = res.info.smallprice
        }
        //3
        single.push(res.num);
        //4
        single.push(number);
        //5
        single.push(price);
        total.push(single);
        compute();
        //console.log(total);
        $(table).appendTo("#buyinfo");
    }
    /**
     * 删除某个商品
     * */
    function tabledel(id,num) {
        var tableid = id + String(num);
        for(var i=0;i<total.length;i++){
            if(contains(total[i],id) && contains(total[i],String(num))){
                total.splice(i,1);
                $("#table"+tableid+"").remove();
            }
        }
        compute();
        //console.log(total);
    }
    /**
     * 购买+1
     * */
    function plus(id,num) {
        var number = String(num);
        var numid = id + number;
        if(ifArrVal(total,id) && ifArrVal(total,number)){
            for(var i=0;i<total.length;i++){
                if(contains(total[i],id) && contains(total[i],number)){
                    total[i][4] += 1;
                    total[i][5] += total[i][2];
                    $("#num"+numid).val(total[i][4]);
                }
            }
        }
        compute();
    }
    /**
     * 购买-1
     * */
    function reduce(id,num) {
        var number = String(num);
        var numid = id + number;
        if(ifArrVal(total,id) && ifArrVal(total,number)){
            for(var i=0;i<total.length;i++){
                if(contains(total[i],id) && contains(total[i],number)){
                    if(total[i][4] == 1){
                        total[i][4] == 1;
                        total[i][5] = total[i][2];
                        return ;
                    }
                    total[i][4] -= 1;
                    total[i][5] -= total[i][2];
                    $("#num"+numid).val(total[i][4]);
                }
            }
        }
        compute();
    }
    /**
     * 总金额
     * */
    function compute() {
        var teaprice = 0;
        for(var i=0;i<total.length;i++){
            teaprice = teaprice +total[i][5];
        }
        $("#tal").html(teaprice.toFixed(1));
        //console.log(total);
    }
    /**
     * 结算
     * */
    function settlement(id) {
        var totalprice = $("#tal").html();
        var sid = id;
        if(!totalprice){
            layer.alert('请先购买商品在结算');
            return;
        }
        $.ajax({
            url:"{:url('index/selltea/settlement')}",
            data:{
                'total':arrayToJson(total),
                'totalprice':totalprice,
                'sid':sid
            },
            type:"post",
            dataType:"json",
            success:function (res) {
                if(res.success){
                    layer.msg(res.success,{icon:1,time:2000},function () {
                        window.location.reload();
                    })
                }else if(res.error){
                    layer.msg(res.error,{icon:5,time:5000});
                }
            }
        });
    }
    /**
     * 判断某个数是否在多维数组中
     */
    function ifArrVal(arr,value){
        //多维数组判断是否存在某值
        for(var i = 0;i < arr.length;i++){
            //判断是否为多维数组
            if(arr[i] instanceof Array){
                if(jQuery.inArray( value, arr[i] )!=-1){
                    return true;
                }
            }
        }
        //不存在
        return false;
    }
    /**
     *  判断某个值是否在数组中
     */
    function contains(arr, obj) {
        //数组的长度
        var i = arr.length;
        while (i--) {
            if (arr[i] === obj) {
                //存在
                return true;
            }
        }
        //不存在
        return false;
    }
    /**
     * 将二维数组转为 json 字符串
     */
    function arrayToJson(o) {
        var r = [];
        if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
        if (typeof o == "object") {
            if (!o.sort) {
                for (var i in o)
                    r.push(i + ":" + arrayToJson(o[i]));
                if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                    r.push("toString:" + o.toString.toString());
                }
                r = "{" + r.join() + "}";
            } else {
                for (var i = 0; i < o.length; i++) {
                    r.push(arrayToJson(o[i]));
                }
                r = "[" + r.join() + "]";
            }
            return r;
        }
        return o.toString();
    }

    /**
     * 查看购买记录
     * */
    function look(id) {
        window.location.href = "{:url('index/selltea/index')}?sid="+id;
    }
    /**
     * 统计
     * */
    function count(id) {
        window.location.href = "{:url('index/teacount/index')}?sid="+id;
    }

    /**
     * 移入
     * */
    function over(th) {
        if(th.id == 'add'){
            $("#"+th.id).css("color","#31B0D5");
        }else if(th.id == 'del'){
            $("#"+th.id).css("color","#d43f3a");
        }else if(th.id == 'edit'){
            $("#"+th.id).css("color","#d58512");
        }else{
            $("#"+th.id).css("color","#0000CD");
        }

    }
    /**
     * 离开
     * */
    function out(th) {
        $("#"+th.id).css("color","");
    }
</script>
</html>